package com.tao.schedule;

import com.tao.constants.SystemConstant;
import com.tao.entity.Help;
import com.tao.enums.AppHttpCodeEnum;
import com.tao.service.HelpService;
import com.tao.utils.RedisCache;
import com.tao.vo.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author  诸葛先生
 * 功能：定时器任务
 */
@Component
public class UpdateViewCountJob {

    @Autowired
    RedisCache redisCache;

    @Autowired
    HelpService helpService;

    @Scheduled(cron = "0 0/10 * * * ?") //每间隔5s更新一次
    public ResponseResult updateViewCount() {
        //获取redis中的浏览量
        Map<String, Integer> viewCountMap = redisCache.getCacheMap(SystemConstant.HELP_VIEW_COUNT);
        List<Help> helps = viewCountMap.entrySet()
                .stream()
                .map(item -> new Help(Long.valueOf(item.getKey()), item.getValue()))
                .collect(Collectors.toList());
        //更新到数据库中
        boolean is_Success = helpService.updateBatchById(helps);
        if (is_Success) {
            return ResponseResult.okResult(200,"操作成功");
        } else {
            return ResponseResult.errorResult(AppHttpCodeEnum.FAILURE);
        }
    }
}
